<?php

namespace App\Http\Controllers;

use App\Http\Resources\Account;
use App\Models\User;
use Illuminate\Http\Request;

class AccountController extends Controller
{
    /**
     * 账号、密码登录
     *
     * @param Request $request
     * @return Account|\Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            'username' => 'required',
            'password' => 'required',
        ]);
    
        if (! $user = $this->hasValidCredentials($request)) {
            return invalidation(trans('auth.failed'));
        }
        
        return new Account($user, true);
    }
    
    /**
     * 获取当前登录用户的信息，没登录时，返回空对象
     *
     * @param Request $request
     * @return Account|array
     */
    public function show(Request $request)
    {
        $user = $request->user('api');
        if (empty($user)) {
            return $this->wrapData();
        }

        return new Account($user);
    }
    
    /**
     * 退出
     *
     * @param Request $request
     */
    public function logout(Request $request)
    {
        // 暂不刷新 token
//        $user = $request->user();
//        $user->refreshApiToken();
//        $user->save();
    }
    
    /**
     * 验证账号、密码是否正确
     *
     * @param Request $request
     * @return bool|User 账号、密码正确的话，返回 \App\Models\User 对象
     */
    protected function hasValidCredentials(Request $request)
    {
        $inputs = $request->only('username', 'password');
        
        if ($this->isReviewer($inputs)) {
            $user = User::findOrFail(config('mall.reviewer_user_id'));
            
            return $user;
        }
        
        return false;
    }
    
    /**
     * 是否为审核账号
     *
     * @param array $params
     * @return bool
     */
    protected function isReviewer($params)
    {
        return config('mall.reviewer_username') == $params['username'] && config('mall.reviewer_password') == $params['password'];
    }
}
